﻿using AutoMapper;
using DongFangGuoKai.WMSPlatform.Commn.ApiResultModule;
using DongFangGuoKai.WMSPlatform.Core;
using DongFangGuoKai.WMSPlatform.Domain.AGVModels;
using DongFangGuoKai.WMSPlatform.Domain.HZJLYModel;
using DongFangGuoKai.WMSPlatform.Domain.Models;
using DongFangGuoKai.WMSPlatform.Service.User.DTO;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;

namespace DongFangGuoKai.WMSPlatform.Service.User
{
    public class UserService : IUserService
    {
        private readonly Repository<t_User> userrepost;
        private readonly Repository<UserColors> usercolorrepost;
        private readonly Repository<t_UserRole> userRolerepost;
        private readonly IMapper mapper;

        public UserService(Repository<t_User> userrepost,
           
            IMapper mapper)
        {
            this.userrepost = userrepost;
            usercolorrepost = userrepost.ChangeRepository<Repository<UserColors>>();
            userRolerepost = userrepost.ChangeRepository<Repository<t_UserRole>>();
            this.mapper = mapper;
        }
        /// <summary>
        /// 判断登录
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public LoginRes GetLogin(LoginDto m)
        {
            try
            {
                var obj = userrepost.GetFirst(x => x.UserName == m.userName);
                if (obj != null)
                {
                    if (obj.Pwd == m.userPassword && obj.Status == 1)
                    {
                        LoginRes loginRes = new LoginRes();
                        loginRes.userName = obj.UserName;
                        loginRes.userId = obj.Id;
                        var usercolor = usercolorrepost.GetFirst(u=>u.UserId == obj.Id);
                        if (usercolor != null && usercolor.ShowColor != 5 && usercolor.ShowColor != 10)
                        {
                            loginRes.showColor = usercolor.ShowColor;
                            loginRes.showColorName = usercolor.ShowColorName;
                        }
                        else
                        {
                            loginRes.showColor = -1;
                            loginRes.showColorName = null;
                        }
                        return loginRes;
                    }
                }
                return null;
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 用户选择颜色
        /// </summary>
        /// <param name="selectColorDTO"></param>
        /// <returns></returns>
        public SelectColorDTO? SelectColor(SelectColorDTO selectColorDTO, out string errMsg)
        {
            SelectColorDTO selectColor = new SelectColorDTO();
            errMsg = string.Empty;
            var UserColor = usercolorrepost.GetList();
            if (UserColor == null)
            {
                errMsg = "没有数据！";
                return null;
            }
            var IsUser = UserColor.FirstOrDefault(u=>u.UserId == selectColorDTO.userId);
            if (IsUser != null)
            {
                errMsg = "该用户已拥有颜色！";
                return null;
            }

            var color = UserColor.FirstOrDefault(u => u.UserId != null && u.ShowColor == selectColorDTO.showColor);
            if (color != null)
            {
                errMsg = "颜色已被占用";
                return null;
            }
            color =  usercolorrepost.GetFirst(c => c.ShowColor == selectColorDTO.showColor);
            if (color == null)
            {
                errMsg = "未查询到此颜色";
                return null;
            }
            color.ColorState = 1;
            color.UserId = selectColorDTO.userId;
            if (!usercolorrepost.Update(color))
            {
                errMsg = "修改颜色状态失败";
                return null;
            }
            errMsg = "请求成功";
            selectColor.userId = selectColorDTO.userId;
            selectColor.showColor = color.ShowColor;
            selectColor.showColorName = color.ShowColorName;
            return selectColor;
        }

        /// <summary>
        /// 用户移除颜色
        /// </summary>
        /// <param name="selectColorDTO"></param>
        /// <returns></returns>
        public bool RemoveColor(SelectColorDTO selectColorDTO,out string errMsg)
        {
            errMsg = string.Empty;
            var UserColor = usercolorrepost.GetList();
            if (UserColor == null)
            {
                errMsg = "没有数据！";
                return false;
            }
            var color = UserColor.FirstOrDefault(r => r.ShowColor == selectColorDTO.showColor && r.UserId == selectColorDTO.userId);
            if (color == null)
            {
                errMsg = "用户没有需要移除的颜色或移除的颜色不对";
                return false;
            }
            color.UserId = null;
            color.ColorState = 0;
            if (!usercolorrepost.Update(color))
            {
                errMsg = "移除颜色失败";
                return false;
            }
            errMsg = "移除颜色成功";
            return true;
        }

        public bool AddUser(UserRoleDTO m,out string errMsg)
        {
            //使用事务的原子性
            errMsg = "添加失败";
            try
            {
                userrepost.AsTenant().BeginTran();
                var obj = userrepost.GetFirst(x => x.UserName == m.UserName);
                if (obj != null)
                {
                    errMsg = $"用户{m.UserName}已存在！";
                    return false;
                }
                //添加用户
                var user = new t_User();
                user = mapper.Map<t_User>(m);
                user.CreateDate = DateTime.Now;
                if (!userrepost.Insert(user))
                {
                    userrepost.AsTenant().RollbackTran();
                    return false;
                }
                //循环遍历角色
                foreach (var item in m.RoleIds.Split(','))
                {
                    var ur = new t_UserRole();
                    ur.UserId = user.Id;
                    ur.RoleId = Convert.ToInt32(item);
                    if (!userRolerepost.Insert(ur))
                    {
                        userrepost.AsTenant().RollbackTran();
                        return false;
                    }
                }
                userrepost.AsTenant().CommitTran();
                return true;
            }
            catch (Exception ex)
            {
                userrepost.AsTenant().RollbackTran();
                errMsg += ex.Message;
                return false;
            }
        }

        public List<t_User> GetUserList(string uname, int rid, int state, int pageIndex, int pageSize, out int totalCount)
        {
            try
            {
                //去除跟踪状态-提高查询速度
                var ulist = userrepost.GetList();
                if (!string.IsNullOrEmpty(uname))
                {
                    ulist = ulist.Where(x => !string.IsNullOrEmpty(x.UserName) && x.UserName.Contains(uname)).ToList();
                }

                if (state != 3)
                {
                    ulist = ulist.Where(x => x.Status == state).ToList();
                }

                var urlist = userRolerepost.GetList();
                if (rid != 0)
                {
                    urlist = urlist.Where(x => x.RoleId == rid).ToList();
                }

                var list = (from u in ulist
                            join ur in urlist
                            on u.Id equals ur.UserId
                            select u).Distinct();
                totalCount = list.Count();
                return list.OrderBy(x => x.CreateDate).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
            catch (Exception)
            {

                throw;
            }
        }

        public UserRoleDTO? URById(int uid)
        {
            try
            {
                var uobj = userrepost.GetFirst(s=>s.Id== uid);
                if (uobj != null)
                {
                    UserRoleDTO urdto = new UserRoleDTO();
                    urdto = mapper.Map<UserRoleDTO>(uobj);
                    var ur = userRolerepost.GetList(x => x.UserId == uid);
                    if (ur.Count() > 0)
                    {
                        foreach (var item in ur)
                        {
                            urdto.RoleIds += item.RoleId + ",";
                        }
                        urdto.RoleIds = urdto.RoleIds.TrimEnd(',');
                    }
                    return urdto;
                }
                return null;
            }
            catch (Exception)
            {

                throw;
            }
        }

        public bool UpdUser(UserRoleDTO m, out string errMsg)
        {
            errMsg = "修改失败";
            using var trans = new TransactionScope();
            try
            {
                var list = userrepost.GetFirst(x => x.Id != m.Id && x.UserName == m.UserName);

                if (list != null)
                {
                    errMsg += $"找不到用户{m.UserName}";
                    return false;
                }
                //更新要修改的信息
                var user = new t_User();
                user = mapper.Map<t_User>(m);
                user.ModifyDate = DateTime.Now;
                if (!userrepost.Update(user))
                {
                    trans.Dispose();
                    return false;
                }
                

                //获取当前用户的所有角色
                var urlist = userRolerepost.GetList(x => x.UserId == user.Id);
                if (urlist.Any())
                {
                    //删除当前用户的所有角色
                    if (!userRolerepost.Delete(urlist))
                    {
                        trans.Dispose();
                        return false;
                    }
                }
                foreach (var item in m.RoleIds.Split(','))
                {
                    var userRole = new t_UserRole();
                    userRole.UserId = m.Id;
                    userRole.RoleId = Convert.ToInt32(item);
                    if (!userRolerepost.Insert(userRole))
                    {
                        trans.Dispose();
                        return false;
                    }
                }
                trans.Complete();
                return true;
            }
            catch (Exception ex)
            {
                //事务回滚
                trans.Dispose();
                errMsg += ex.Message;
                return false;
            }
            
        }

        public bool DelUser(int uid, out string errMsg)
        {
            errMsg = "删除失败！";
            using var trans = new TransactionScope();
            try
            {
                var uobj = userrepost.GetFirst(s => s.Id == uid);
                if (uobj != null)
                {
                    if (!userrepost.Delete(uobj))
                    {
                        trans.Dispose();
                        return false;
                    }
                    var urlist = userRolerepost.GetList(x => x.UserId == uid);
                    if (!userRolerepost.Delete(urlist))
                    {
                        trans.Dispose();
                        return false;
                    }
                    return true;
                }
                errMsg += "id有误,找不到改用户";
                return false;
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
